package com.amumu.drama.common.modules.service.impl;

import com.amumu.drama.common.config.AliyunProperties;
import com.amumu.drama.common.modules.service.VerifyService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Service
//@EnableConfigurationProperties(AliyunProperties.class)
public class AliyunVerifyServiceImpl implements VerifyService {

    private static final Logger LOGGER = LoggerFactory.getLogger(AliyunVerifyServiceImpl.class);

    @Autowired
    private AliyunProperties idCardProperties;

    @Override
    public String verifyIdCard(String realName, String idNumber) {
        try {
            LOGGER.debug("verifyIdCard.execute realName:" + realName + " idNumber:" + idNumber);
            String result = this.postData(realName, idNumber);
            LOGGER.debug("verifyIdCard.execute result:" + result);
            return result;
        } catch (Exception e) {
            LOGGER.error("verifyIdCard.execute realName:" + realName + " idNumber:" + idNumber, e);
        }
        return null;
    }

    public String postData(String name, String idNo) throws Exception {
        String result = "";
        HttpPost httpPost = new HttpPost("https://idenauthen.market.alicloudapi.com/idenAuthentication");
        httpPost.setHeader("Authorization", "APPCODE " + idCardProperties.getAppCode());

        List<BasicNameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("name", name));
        params.add(new BasicNameValuePair("idNo", idNo));
        httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    System.out.println("Request failed: " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
                    return null;
                }

                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                }
            }
        }
        return result;
    }
}
